package com.sf.sql;

import java.lang.reflect.Field;

import com.sf.entity.Company;

import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteDatabase.CursorFactory;
import android.database.sqlite.SQLiteOpenHelper;

public class DBHelper extends SQLiteOpenHelper {

	final static String NAME = "data.db";
	final static int VERSION = 1;

	public DBHelper(Context context) {
		super(context, NAME, null, VERSION);
	}

	public DBHelper(Context context, String name, CursorFactory factory,
			int version) {
		super(context, name, factory, version);
	}

	@Override
	public void onCreate(SQLiteDatabase db) {
		db.execSQL(createTable(Company.class, "company_store"));
	}

	private <T> String createTable(Class<T> c) {
		return createTable(c, c.getSimpleName());
	}

	private <T> String createTable(Class<T> c, String tableName) {
		StringBuffer sb = new StringBuffer();
		sb.append("create table if not exists " + tableName + " "
				+ "(_ID INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL,");
		Field[] fields = c.getFields();
		for (Field field : fields) {
			if (!field.getName().equals("_id")
					&& !"CREATOR".equals(field.getName())
					&& !"CONTENTS_FILE_DESCRIPTOR".equals(field.getName())
					&& !"PARCELABLE_WRITE_RETURN_VALUE".equals(field.getName())) {
				sb.append(field.getName() + " TEXT,");
			}

		}
		sb.deleteCharAt(sb.length() - 1);
		sb.append(");");
		return sb.toString();
	}

	@Override
	public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {

	}

}
